// Set

// 1. 基本语法

// 定义一个空的 Set 实例
let s1 = new Set();
console.log(s1);

// 也可以在实例化的同时传入默认的数据
let s2 = new Set([1, 2, 3, 2]);
console.log(s2);

console.log(s2.size);

// 2. 常用方法

// 添加数据 add

// s1.add("hello");
// s1.add("world");
console.log(s1);

// 链式写法
s1.add("hello").add("world");
console.log(s1);

// 删除数据

// 分两种情况：一种是删除指定的数据；另一种是删除全部数据

s1.delete("hello");
console.log(s1);

s1.clear();
console.log(s1);

// 统计数据

// 判断是否包含指定的数据成员
console.log(s1.has("hello"));

s1.add("hello");
console.log(s1.has("hello"));

// 计算数据的总数
console.log(s1.size);

// 3. 应用场景

// 数组去重
let arr = [1, 2, 3, 4, 2, 3];
console.log(arr);

console.log(new Set(arr));

// 合并去重
let arr1 = [1, 2, 3, 4];
let arr2 = [2, 3, 4, 5, 6];

let arr3 = [...arr1, ...arr2];
console.log(arr3);

console.log(new Set(arr3));

console.log(new Set([...arr1, ...arr2]));

// 交集
let s3 = new Set(arr1);
let s4 = new Set(arr2);

let result1 = new Set(arr1.filter(item => {
    return s4.has(item)
}));

// 简写
let result2 = new Set(arr1.filter(item => s4.has(item)));
console.log(result1, result2);

// 差集
let s5 = new Set(arr1.filter(item => !s4.has(item)));
let s6 = new Set(arr2.filter(item => !s3.has(item)));
console.log(s5, s6);

console.log([...s5, ...s6]);

// 4. 遍历方式

let s7 = new Set([1, 2, 3, 4]);
s7.forEach((value, key) => {
    console.log(value, key);
})

for(let item of s7) {
    console.log(item);
}

for(let key of s7.keys()) {
    console.log(key);
}

for(let value of s7.values()) {
    console.log(value);
}

for(let item of s7.entries()) {
    console.log(item[0], item[1]);
}

for(let [key, value] of s7.entries()) {
    console.log(key, value);
}


// 5. WeakSet

let ws1 = new WeakSet();
// ws1.add("abc"); // TypeError: Invalid value used in weak set

let ws2 = new WeakSet();
let obj1 = {
    name: "jayjun"
}

let obj2 = {
    age: 18
}

ws2.add(obj1);
ws2.add(obj2);

console.log(ws2);

ws2.delete(obj1);
console.log(ws2);

console.log(ws2.has(obj1));
console.log(ws2.has(obj2));

// WeakSet 不支持遍历，也没有size属性。
// ws2.forEach(item => {
//     console.log(item);  //TypeError: ws2.forEach is not a function
// })


// 思考题

let ws = new WeakSet();
ws.add({
    name: "jayjun"
});
ws.delete({
    name: "jayjun"
});
console.log(ws);








